package com.ezia.coreservices.charging.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.HmacUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ezia.coreservices.charging.config.StarCharingConfig;
import com.ezia.coreservices.charging.service.TestService;
import com.ezia.coreservices.charging.utils.AesEncryptionUtil;
import com.ezia.coreservices.charging.utils.HttpClientUtil;
import com.ezia.coreservices.charging.utils.ResultMsg;
import com.ezia.coreservices.charging.utils.ResultStatusCode;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONObject;



@RestController
@RequestMapping("test")
public class TestController {
	
	private static final Logger logger = LoggerFactory.getLogger(TestController.class);

	
	@Autowired 
	private TestService testservice;
	
	@Autowired
	private StarCharingConfig starcharingconfig;
	
	
	
	@RequestMapping("getUser")
	public Object getUser() {
		Object Result = testservice.findAll();
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.Success.getRespCode(), ResultStatusCode.Success.getRespMsg(),
				Result);
		return resultMsg;
	}
	
	
	@RequestMapping("testYml")
	public Object testYml() {
		logger.info(starcharingconfig.getOperatorId());
		ResultMsg resultMsg = new ResultMsg(ResultStatusCode.Success.getRespCode(), ResultStatusCode.Success.getRespMsg(),
				starcharingconfig.getOperatorId());
		return resultMsg;
	}
	
	/**
	 * 获取互联互通Token
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping("queryToken")
	@SuppressWarnings("unchecked")
	public String query_token() throws Exception {
		logger.info(starcharingconfig.getOperatorId());
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		mEncryptData.put("OperatorID", starcharingconfig.getOperatorId());
		mEncryptData.put("OperatorSecret", starcharingconfig.getOperatorSecret());
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_token";
		logger.info("requestUrl:"+url);
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString()));
		logger.info("mResponse:" + mResponse);
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		Map<String, Object> mData = (Map<String, Object>) JSONObject.fromObject(mResponse.get("Data").toString());
		logger.info("AccessToken:" + mData.get("AccessToken"));
		return mData.get("AccessToken").toString();
	}
	
	
	/**
	 * 查询充电站信息
	 * 
	 * @param token
	 * @return
	 */
	@RequestMapping("queryStationInfo")
	@SuppressWarnings("unchecked")
	public String query_stations_info(String token) throws Exception {
		// 传入参数
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		//mEncryptData.put("LastQueryTime", "");
		mEncryptData.put("PageNo", "1");
		mEncryptData.put("PageSize", "10");
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_stations_info";
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString(), token));
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		return mResponse.get("Data").toString();
	}
	
	
	/**
	 * 批量查询设备实时状态
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@RequestMapping("queryStationStatus")
	@SuppressWarnings("unchecked")
	public String query_stations_status(String token,ArrayList<String> stationid) throws Exception{
		// 传入参数
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		//mEncryptData.put("LastQueryTime", "");
		//mEncryptData.put("PageNo", "1");
		ObjectMapper om = new ObjectMapper();
		mEncryptData.put("StationIDs", stationid);
		om.writeValueAsString(mEncryptData);
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_station_status";
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString(), token));
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		return mResponse.get("Data").toString();
		
	}
	
	/**
	 * 互联互通控制接口：请求设备认证
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@RequestMapping("queryEquipAuth")
	@SuppressWarnings("unchecked")
	public String query_equip_auth(String token,String EquId,String ConnectorId) throws Exception{
		// 传入参数
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		//mEncryptData.put("LastQueryTime", "");
		mEncryptData.put("EquipAuthSeq", EquId);
		mEncryptData.put("ConnectorID", ConnectorId);
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_equip_auth";
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString(), token));
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		return mResponse.get("Data").toString();

	}
	
	/**
	 * 互联互通控制接口：启动充电
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@RequestMapping("queryStartCharge")
	@SuppressWarnings("unchecked")
	public String query_start_charge(String token,String orderId,String ConnectorId,String QRCode) throws Exception {
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		//mEncryptData.put("LastQueryTime", "");
		mEncryptData.put("StartChargeSeq", orderId);
		mEncryptData.put("ConnectorID", ConnectorId);
		mEncryptData.put("QRCode", QRCode);
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_start_charge";
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString(), token));
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		return mResponse.get("Data").toString();
	}
	
	/**
	 * 互联互通控制接口：停止充电
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@RequestMapping("queryStopCharge")
	@SuppressWarnings("unchecked")
	public String query_stop_charge(String token,String orderId,String ConnectorId) throws Exception {
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		//mEncryptData.put("LastQueryTime", "");
		mEncryptData.put("StartChargeSeq", orderId);
		mEncryptData.put("ConnectorID", ConnectorId);
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_stop_charge";
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString(), token));
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		return mResponse.get("Data").toString();
	}
	
	/**
	 * 互联互通控制接口：查询充电状态
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@RequestMapping("queryequipChargeStatus")
	@SuppressWarnings("unchecked")
	public String query_equip_Charge_Status(String token,String orderId) throws Exception {
		Map<String, Object> mEncryptData = new HashMap<String, Object>();
		//mEncryptData.put("LastQueryTime", "");
		mEncryptData.put("StartChargeSeq", orderId);
		String data = encryptData(mEncryptData);
		String timeStamp = getTimestamp();
		Map<String, Object> mRequest = new HashMap<String, Object>();
		mRequest.put("OperatorID", starcharingconfig.getOperatorId());
		mRequest.put("Data", data);
		mRequest.put("TimeStamp", timeStamp);
		mRequest.put("Seq", starcharingconfig.getSEQ());
		mRequest.put("Sig", getSign(data, timeStamp));
		JSONObject requestData = JSONObject.fromObject(mRequest);
		logger.info("requestData:" + requestData.toString());
		String url = starcharingconfig.getServerUrl() + "query_equip_charge_status";
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(HttpClientUtil.sendHttpPostJson(url, requestData.toString(), token));
		mResponse.put("Data", decryptData((String) mResponse.get("Data")));
		return mResponse.get("Data").toString();
	}
	
	

	/**
	 * 加密传输数据
	 * 
	 * @param
	 * @return 加密后的字符串
	 */
	private String encryptData(Map<String, Object> mEncryptData) throws Exception {
		return AesEncryptionUtil.Encrypt(JSONObject.fromObject(mEncryptData).toString(), starcharingconfig.getDataSecret(), starcharingconfig.getDataSecretIV());
	}

	/**
	 * 解密传输数据
	 * 
	 * @param
	 * @return 解密后的字符串
	 */
	private String decryptData(String data) throws Exception {
		// 解密返回数据
		String deString = AesEncryptionUtil.Decrypt(data, starcharingconfig.getDataSecret(), starcharingconfig.getDataSecretIV());
		return deString;
	}
	
	/**
	 * 获取签名
	 * 
	 * @param data      加密后的传输数据
	 * @param timeStamp 时间戳字符串
	 * @return 
	 */
	private String getSign(String data, String timeStamp) {
		String signData = HmacUtils.hmacMd5Hex(starcharingconfig.getSigSecret(), starcharingconfig.getOperatorId() + data + timeStamp + starcharingconfig.getSEQ()).toUpperCase();
		return signData;
	}

	/**
	 * 获取时间戳字符串123
	 * 
	 * @param
	 * @return
	 */
	private String getTimestamp() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		Timestamp d = new Timestamp(System.currentTimeMillis());
		return df.format(d);
	}
	

}
